package com.waidi.clothespad.ui;
import android.content.Intent;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.waidi.clothespad.R;
import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.DevData;
import com.waidi.clothespad.common.MessageToUi;
import com.waidi.clothespad.common.MyToast;
import com.waidi.clothespad.common.QRCodeUtil;
import com.waidi.clothespad.common.VerData;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import android.provider.Settings;

/**
 * Created by Administrator on 2017/5/4.
 */

public class SettingDialog extends Dialog{


    Unbinder unbinder;
    private View view;

    private static final String TAG = "SettingDialog";
    @BindView(R.id.btn_save)
    Button btn_arg_save;
   // @BindView(R.id.server_addr)
    private  EditText net_server_addr;
    //@BindView(R.id.server_port)
    private EditText net_web_addr;
    //@BindView(R.id.dev_id)
    private EditText dev_dev_id;


    private SettingDialogHandler handlersetting;
    private Context context;
    private Handler handler0;
    private boolean loadedversioned;


    LinearLayout ll_device ;
    LinearLayout ll_system ;
    LinearLayout ll_about ;


    LinearLayout ll_underline_device ;
    LinearLayout ll_underline_system ;
    LinearLayout ll_underline_about;

    LinearLayout ll_content_device ;
    LinearLayout ll_content_system ;
    LinearLayout ll_content_about;

    TextView tv_device ;
    TextView tv_system ;
    TextView tv_about;
    TextView tv_ver;
    Button btn_cancel;
    Button btn_save;
    Button qrcode_info_refush;

    ImageView qrcode_bitmp;
    TextView qrcode_content;

    private boolean isDrawed = false;




    public SettingDialog(@NonNull Context context,Handler handlerin) {
        super(context);
        this.context = context;
        this.handler0 = handlerin;
        this.handlersetting = new SettingDialogHandler();
        loadedversioned = false;
        getQrCodeInfo();//default loading
    }

    public SettingDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
        this.handlersetting = new SettingDialogHandler();
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
/*        setContentView(R.layout.layer_system_setting);
        ButterKnife.bind(this);*/
        net_server_addr = (EditText) findViewById(R.id.server_addr);
        net_web_addr = (EditText) findViewById(R.id.web_addr);
        dev_dev_id = (EditText) findViewById(R.id.dev_id);
        isDrawed = true;

        init();
    }

    private void init() {

        View view = LayoutInflater.from(context).inflate(R.layout.layer_system_setting, null);
        ll_device = (LinearLayout) view.findViewById(R.id.ll_device);
        ll_system = (LinearLayout) view.findViewById(R.id.ll_system);
        ll_about = (LinearLayout) view.findViewById(R.id.ll_about);

        qrcode_bitmp = (ImageView) view.findViewById(R.id.qrcode_bitmp);
        qrcode_content = (TextView) view.findViewById(R.id.qrcode_content);


        ll_underline_device = (LinearLayout) view.findViewById(R.id.ll_underline_device);
        ll_underline_system = (LinearLayout) view.findViewById(R.id.ll_underline_system);
        ll_underline_about = (LinearLayout) view.findViewById(R.id.ll_underline_about);


        ll_content_device = (LinearLayout) view.findViewById(R.id.ll_content_device);
        ll_content_system = (LinearLayout) view.findViewById(R.id.ll_content_system);
        ll_content_about = (LinearLayout) view.findViewById(R.id.ll_content_about);


        tv_device = (TextView) view.findViewById(R.id.tv_device);
        tv_system = (TextView) view.findViewById(R.id.tv_system);
        tv_about = (TextView) view.findViewById(R.id.tv_about);
        tv_ver = (TextView) view.findViewById(R.id.tv_ver);






        Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
        Button btn_save = (Button) view.findViewById(R.id.btn_save);
        Button btn_check = (Button) view.findViewById(R.id.btn_check_version);
        Button qrcode_info_refush =(Button) view.findViewById(R.id.qrcode_info_refush);



        ll_device.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_device.setTextColor(Color.parseColor("#1EB4A8"));
                tv_system.setTextColor(Color.parseColor("#aaaaaa"));
                tv_about.setTextColor(Color.parseColor("#aaaaaa"));

                ll_underline_device.setVisibility(View.VISIBLE);
                ll_underline_system.setVisibility(View.INVISIBLE);
                ll_underline_about.setVisibility(View.INVISIBLE);

                ll_content_device.setVisibility(View.VISIBLE);
                ll_content_system.setVisibility(View.INVISIBLE);
                ll_content_about.setVisibility(View.INVISIBLE);
            }
        });
        ll_system.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_system.setTextColor(Color.parseColor("#1EB4A8"));
                tv_device.setTextColor(Color.parseColor("#aaaaaa"));
                tv_about.setTextColor(Color.parseColor("#aaaaaa"));


                ll_underline_system.setVisibility(View.VISIBLE);
                ll_underline_device.setVisibility(View.INVISIBLE);
                ll_underline_about.setVisibility(View.INVISIBLE);

                ll_content_system.setVisibility(View.VISIBLE);
                ll_content_device.setVisibility(View.INVISIBLE);
                ll_content_about.setVisibility(View.INVISIBLE);

            }
        });

        ll_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_about.setTextColor(Color.parseColor("#1EB4A8"));
                tv_device.setTextColor(Color.parseColor("#aaaaaa"));
                tv_system.setTextColor(Color.parseColor("#aaaaaa"));

                ll_underline_about.setVisibility(View.VISIBLE);
                ll_underline_system.setVisibility(View.INVISIBLE);
                ll_underline_device.setVisibility(View.INVISIBLE);


                ll_content_about.setVisibility(View.VISIBLE);
                ll_content_device.setVisibility(View.INVISIBLE);
                ll_content_system.setVisibility(View.INVISIBLE);

            }
        });

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //可自己实现点击响应
                SaveAppConfig();
                dismiss();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //可自己实现点击响应
                dismiss();
            }
        });

        btn_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //可自己实现点击响应
                getApkVersion(0);

            }
        });


        qrcode_info_refush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getQrCodeInfo();
            }
        });

        /*带logo*/
        /*  boolean success = QRCodeUtil.createQRImage("YYYYYYYY", 300, 300,
        BitmapFactory.decodeResource(context.getResources(), R.drawable.logo),
                Config.Clothesath+"uuid.png");*/

        try
        {
        String qrfile = Config.Clothesath+"/uuid.png";
        String uuid = Config.getUniquePsuedoID();
        Log.i(TAG,uuid);
        qrcode_content.setText(uuid);
        boolean success = QRCodeUtil.createQRImage(uuid, 150, 150, null, qrfile);
        if(success)
        {
            Log.i(TAG,"uuid ok...............");
            qrcode_content.setText(uuid);
            qrcode_bitmp.setImageBitmap(BitmapFactory.decodeFile(qrfile));
        }

        setContentView(view);
        Window dialogWindow = getWindow();
        WindowManager manager = ((Activity) context).getWindowManager();
        WindowManager.LayoutParams params = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        dialogWindow.setGravity(Gravity.CENTER);//设置对话框位置
        Display d = manager.getDefaultDisplay(); // 获取屏幕宽、高度
        params.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.65，根据实际情况调整
        params.height = (int) (d.getHeight() * 0.9); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(params);

        DevData devData = new DevData(context);
        devData.loadAppConfig();
        ((EditText) findViewById(R.id.server_addr)).setText(Config.devConfig.addr.toCharArray(),0,Config.devConfig.addr.length());
        ((EditText) findViewById(R.id.web_addr)).setText(Config.devConfig.web_addr.toCharArray(),0,Config.devConfig.web_addr.length());
        ((EditText) findViewById(R.id.dev_id)).setText(Config.devConfig.devid.toCharArray(),0,Config.devConfig.devid.length());

        ((EditText) findViewById(R.id.line_num)).setText(Config.devConfig.line_num.toCharArray(),0,Config.devConfig.line_num.length());

        tv_ver.setText("V"+Config.ver);


        ((EditText) findViewById(R.id.factoryid)).setText(Config.qrCodeInfo.factory.toCharArray(),0,Config.qrCodeInfo.factory.length());
        ((EditText) findViewById(R.id.workshopid)).setText(Config.qrCodeInfo.workshop.toCharArray(),0,Config.qrCodeInfo.workshop.length());
        ((EditText) findViewById(R.id.lineid)).setText(Config.qrCodeInfo.line.toCharArray(),0,Config.qrCodeInfo.line.length());
        ((EditText) findViewById(R.id.workstationid)).setText(Config.qrCodeInfo.workstation.toCharArray(),0,Config.qrCodeInfo.workstation.length());


        ((EditText) findViewById(R.id.nameid)).setText(Config.qrCodeInfo.name.toCharArray(),0,Config.qrCodeInfo.name.length());
        ((EditText) findViewById(R.id.numid)).setText(Config.qrCodeInfo.num.toCharArray(),0,Config.qrCodeInfo.num.length());

        getQrCodeInfo();//default loading
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public void getQrCodeInfo()
    {
        Toast.makeText(context, "获取设备二维码信息！", Toast.LENGTH_SHORT).show();
        Config A = new Config(context);
        Config.DpsInterface dpsInterface = A.new DpsInterface(Config.devConfig.web_addr);
        String url = dpsInterface.qrcode;
        httpqrcode thread = new httpqrcode(handler0,handlersetting,context,url);
        thread.start();
    }


    public class httpqrcode extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public Handler handlersetting0 = null;
        public String Url = null;

        public httpqrcode(Handler handlerin, Handler handlersettingin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            handlersetting0 = handlersettingin;
            Url = url;

        }
        public void run() {

            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();
            try
            {

                HttpGet httpGet = new HttpGet(Url);

                httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000);//连接时间
                httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
                int code = -1;

                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get orderinfo reponse code: " + Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                }
                else
                {
                    String s = "服务端返回："+code;
                    new MessageToUi().send(20,"exception",s,handlersetting0);
                    return;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                new MessageToUi().send(20,"exception",e.toString(),handlersetting0);
                return;
            }
            try
            {
                JSONObject jsonObj = new JSONObject(result);
                if (jsonObj == null)
                    return;
                else
                {
                    if(jsonObj.has("error")==true)
                    {
                        JSONObject error = jsonObj.optJSONObject("error");
                        String message = error.optString("message");
                        new MessageToUi().send(20,"exception",message,handlersetting0);
                    }
                    else
                    {
                        if(jsonObj.has("data")==true)
                        {
                            JSONObject data = jsonObj.optJSONObject("data");

                            int isBinded;

                            if(data.has("isBinded"))
                            {
                                Config.qrCodeInfo.name = "#未绑定";
                                Config.qrCodeInfo.num ="#未绑定";

                                Config.qrCodeInfo.factory = "#未绑定";
                                Config.qrCodeInfo.workshop ="#未绑定";
                                Config.qrCodeInfo.line ="#未绑定";
                                Config.qrCodeInfo.workstation  ="#未绑定";
                                Config.qrCodeInfo.location="";

                                String ss = "#该设备未绑定！";
                                new MessageToUi().send(30, "info", ss, handlersetting0);
                            }else
                            {
                                Config.qrCodeInfo.name = data.optString("name");
                                Config.qrCodeInfo.num = data.optString("num");
                                String localNum = data.optString("localNum");
                                Config.qrCodeInfo.location = localNum;
                                String s="";
                                if(localNum.length()==6)
                                {
                                    Config.qrCodeInfo.factory = localNum.substring(0, 1);
                                    Config.qrCodeInfo.workshop = localNum.substring(1, 2);
                                    Config.qrCodeInfo.line = localNum.substring(2, 4);
                                    Config.qrCodeInfo.workstation = localNum.substring(4, 6);
                                    s = "设备二维码信息获取成功";
                                    Config.qrCodeInfo.QrCodeInfoWrite();
                                }
                                else
                                {
                                    s = "设备二维码信息获取成功,位置信息有误？";
                                }

                                new MessageToUi().send(30, "info", s, handlersetting0);
                            }
                        }
                    }
                }
            }catch (JSONException e)
            {
                e.printStackTrace();
                new MessageToUi().send(20,"exception",e.toString(),handlersetting0);
                return;
            }
            catch (Exception io)
            {
                io.printStackTrace();
                new MessageToUi().send(20,"exception",io.toString(),handlersetting0);
            }
        }

    }


    public void getApkVersion(int flag)
    {

        if(loadedversioned==true&&flag==1)
        {
            //主界面 定时请求后，已经获取版本号后返回，不再继续请求
            return;
        }

        Toast.makeText(context, "获取软件版本信息！", Toast.LENGTH_SHORT).show();
        Config A = new Config(context);
        Config.DpsInterface dpsInterface = A.new DpsInterface(Config.devConfig.web_addr);
        String url = dpsInterface.update+"?&type=0";


        httpsync thread = new httpsync(handler0,handlersetting,context,url);
        thread.start();

    }

    public class httpsync extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public Handler handlersetting0 = null;
        public String Url = null;

        public httpsync(Handler handlerin, Handler handlersettingin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            handlersetting0 = handlersettingin;
            Url = url;

        }
        public void run() {

            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();

            try
            {
                HttpGet httpGet = new HttpGet(Url);

                httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000);//连接时间
                httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
                int code = -1;

                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get orderinfo reponse code: " + Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                }
                else
                {

                    String s = "服务端返回："+code;
                    new MessageToUi().send(20,"exception",s,handlersetting0);
                    return;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                new MessageToUi().send(20,"exception",e.toString(),handlersetting0);
                return;
            }
            try
            {
                JSONObject jsonObj = new JSONObject(result);
                if (jsonObj == null)
                    return;
                else
                {
                    if(jsonObj.has("error")==true)
                    {
                        JSONObject error = jsonObj.optJSONObject("error");
                        String message = error.optString("message");
                        new MessageToUi().send(20,"exception",message,handlersetting0);
                    }
                    else
                    {
                        if(jsonObj.has("data")==true)
                        {
                            JSONObject data = jsonObj.optJSONObject("data");
                            if(data==null)
                            {
                                String sss = "服务端无APK信息！";
                                loadedversioned = true;
                                new MessageToUi().send(21,"info",sss,handlersetting0);
                                return;
                            }

                            String ver = data.optString("version");
                           if(ver.compareTo(Config.ver)==0)
                            {
                                String ss = "该版本已经是最新！";
                                loadedversioned = true;
                                new MessageToUi().send(21,"info",ss,handlersetting0);

                            }else
                            {
                                float tmp0 = Float.parseFloat(ver);
                                float tmp1 = Float.parseFloat(Config.ver);
                                if(Float.compare(tmp0,tmp1)>0)
                               // if(true)
                                {
                                    String fileurl = data.optString("fileUrl");
                                    Bundle bundle2=new Bundle();
                                    VerData tmp = new VerData();
                                    tmp.ver = ver;
                                    tmp.fileurl = fileurl;
                                    bundle2.putParcelable("update", tmp);
                                    Message msg0;
                                    msg0=handler0.obtainMessage();//每发送一次都要重新获取
                                    msg0.setData(bundle2);
                                    msg0.arg1 = 100;
                                    handler0.sendMessage(msg0);//用handler向主线程发送信息
                                    return;
                                }
                                else  if(Float.compare(tmp0,tmp1)<=0)
                                {
                                    String sss = "服务端APK版本较低！";
                                    loadedversioned = true;
                                    new MessageToUi().send(21,"info",sss,handlersetting0);
                                }
                            }
                        }
                    }
                }
            }catch (JSONException e)
            {
                e.printStackTrace();
                new MessageToUi().send(20,"exception",e.toString(),handlersetting0);
                return;
            }
            catch (Exception io)
            {
                io.printStackTrace();
                new MessageToUi().send(20,"exception",io.toString(),handlersetting0);
            }
        }

    }
    //自定义handler类
    class SettingDialogHandler extends Handler {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg) {
            try {
                Log.i(TAG, Integer.toString(msg.arg1));
                switch (msg.arg1) {

                    case 20:
                        Bundle bundle0 = msg.getData();
                        String exception = bundle0.getString("exception");
                        MyToast.showToast(context, exception);
                        break;
                    case 21:
                        Bundle bundle2 = msg.getData();
                        String info = bundle2.getString("info");
                        MyToast.showToast(context, info);
                        break;
                    case 30:
                        Bundle bundle30 = msg.getData();
                        String info30 = bundle30.getString("info");
                        MyToast.showToast(context, info30);
                        if(isDrawed==false)
                            return;

                        ((EditText) findViewById(R.id.factoryid)).setText(Config.qrCodeInfo.factory.toCharArray(), 0, Config.qrCodeInfo.factory.length());
                        ((EditText) findViewById(R.id.workshopid)).setText(Config.qrCodeInfo.workshop.toCharArray(), 0, Config.qrCodeInfo.workshop.length());
                        ((EditText) findViewById(R.id.lineid)).setText(Config.qrCodeInfo.line.toCharArray(), 0, Config.qrCodeInfo.line.length());
                        ((EditText) findViewById(R.id.workstationid)).setText(Config.qrCodeInfo.workstation.toCharArray(), 0, Config.qrCodeInfo.workstation.length());
                        //
                        ((EditText) findViewById(R.id.nameid)).setText(Config.qrCodeInfo.name.toCharArray(), 0, Config.qrCodeInfo.name.length());
                        ((EditText) findViewById(R.id.numid)).setText(Config.qrCodeInfo.num.toCharArray(), 0, Config.qrCodeInfo.num.length());

                        Config.qrCodeInfo.QrCodeInfoWrite();
                        break;

                    default:
                        break;

                }
            }
            catch ( Exception e)
            {
                e.printStackTrace();
                MyToast.showToast(context,e.toString());
            }
        }
    }



    public void SaveAppConfig()
    {

        String dg_addr = ((EditText) findViewById(R.id.server_addr)).getText().toString();

        if(dg_addr.compareTo(Config.devConfig.addr)!=0)
        {
            Config.dg_server_add_changed = true;
        }
        Config.devConfig.addr = dg_addr;
        Config.devConfig.web_addr = ((EditText) findViewById(R.id.web_addr)).getText().toString();
        Config.devConfig.devid = ((EditText) findViewById(R.id.dev_id)).getText().toString();
        Config.devConfig.line_num = ((EditText) findViewById(R.id.line_num)).getText().toString();

        Config.savedevtxt();

        Log.i(TAG,Config.devConfig.devid+ " "+Config.devConfig.addr+ " "+Config.devConfig.web_addr+ " "+Config.devConfig.line_num);
    }
}
